﻿using Common.Communal;
using ERP.Domain.CustomerSupplier;
using ERP.Domain.Processs;
using ERP.Domain.SalesManagement;
using MediatR;
using Sell.Api.Read.Application.Command.ProcesssCommand;
using Sell.DTO;
using SqlSugar;

namespace Sell.Api.Read.Application.CommandHandlers.ProcesssCommandHandlers
{
    public class ProcessslistCommandHandlers : IRequestHandler<ProcessslistCommand, ApiResult<ApiPaging<processlistdto>>>
    {
        public ISqlSugarClient SqlSugar { get; }
        public ProcessslistCommandHandlers(ISqlSugarClient sqlSugar)
        {
            SqlSugar = sqlSugar;
        }
        /// <summary>
        /// 工序管理列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<ApiPaging<processlistdto>>> Handle(ProcessslistCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<processlistdto>> res = new ApiResult<ApiPaging<processlistdto>>();
            res.Code = EnumCode.Ok;
            res.Message = "工序管理显示成功";
            /// 初始化查询：关联 Procure表和Contract表
            var query = SqlSugar.Queryable<PSrocess>()
                .LeftJoin<ProcessType>((p, s) => p.ProcessTypeId == s.Id)
                .Where(p => p.IsDelete == false).Select(
                (p, s) => new processlistdto
                {
                    DeptName=p.DeptName,
                     ProcessTypeId=p.ProcessTypeId ,
                      Desc = p.Desc,
                       Id=s.Id,
                        IsDelete=p.IsDelete,
                         ProcessCode=p.ProcessCode,
                          ProcessCount=p.ProcessCount,  
                           ProcessName=p.ProcessName,
                            ProcessTypeCode=s.ProcessTypeCode,
                             ProcessTypeName=s.ProcessTypeName,
                              ProcessTypeState=s.ProcessTypeState,
                               State=p.State,
                                User=p.User,
                });
            //SqlSugar分页查询实现
            ApiPaging<processlistdto> result = new ApiPaging<processlistdto>();
            result.TotalCount = query.Count();//查询总记录数
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.pagesize);//计算总页数
            result.Data = query.Skip((request.pageindex - 1) * request.pagesize)//跳过前面的记录
                .Take(request.pagesize)//取指定页大小的记录
                .ToList();//执行查询并转为List
            res.Success(result, "查询成功");
            return res;
        }
    }
}
